import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Class that interacts with database
 * 
 * @author Xiaohui
 * 
 */

public class ConnMaker {
	/**
	 * Connection parameters
	 */
	static String db = "gpstracker";
	static String dbLoginName = "root";
	static String dbLoginPassword = "123456";
	static String tablename = "upload";
	static String url = "jdbc:mysql://localhost/" + db + "?user=" + dbLoginName
			+ "&password=" + dbLoginPassword;
	Connection conn = null;
	StrParser parser;
	static int numConns = 0; // count number of connections

	public ConnMaker() {
		try {
			// register driver
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			// build connection
			conn = DriverManager.getConnection(url);
			numConns++;
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public int getNumConns() {
		return numConns;
	}

	public ResultSet getResultSet() throws Exception {
		String query = "SELECT * FROM " + tablename;
		Statement stmt = conn.createStatement();
		ResultSet rs = stmt.executeQuery(query);
		return rs;
	}

	public void closeConn() {
		try {
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Insert data entries into database
	 * 
	 * @param parser
	 * @throws Exception
	 */
	public void insertDB(StrParser parser) throws Exception {
		String sql = "";

		sql = "INSERT INTO " + tablename
				+ " (imei, uploadtime, Nattr, Eattr) VALUES ('"
				+ parser.getImei() + "', '" + parser.getUploadTime() + "', "
				+ parser.getNattr() + ", " + parser.getEattr() + ")";

//		System.out.println(sql);
		Statement stmt = conn.createStatement();
		stmt.executeUpdate(sql);
		stmt.close();
	}

	public static void main(String[] args) throws Exception {
		for (int i = 0; i < 3; i++) {
			System.out.println(i);
			ConnMaker conmaker = new ConnMaker();
			// ResultSet rs = conmaker.getResultSet();
			// while (rs.next()) {
			// System.out.println(rs.getString("imei"));
			// }
			// rs.close();
			conmaker.insertDB(StrParser.getExampleParser());
			conmaker.closeConn();
		}
	}

}
